package com.doubao.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.common.result.Result;
import com.doubao.device.dto.AIModelInfoDTO;
import com.doubao.device.dto.ApiConfigDTO;
import com.doubao.device.dto.SmartDeviceDTO;
import com.doubao.device.dto.TagDTO;
import com.doubao.device.dto.VoiceConfigDTO;
import com.doubao.device.dto.request.CreateDeviceRequest;
import com.doubao.device.dto.request.DeviceQueryRequest;
import com.doubao.device.dto.request.UpdateDeviceRequest;
import com.doubao.device.entity.SmartDevice;
import com.doubao.device.entity.SmartDeviceTagRelation;
import com.doubao.device.mapper.SmartDeviceMapper;
import com.doubao.device.mapper.UserDeviceCollectionMapper;
import com.doubao.device.service.DeviceApiService;
import com.doubao.device.service.DeviceVoiceService;
import com.doubao.device.service.SmartDeviceService;
import com.doubao.device.service.SmartDeviceTagService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 智能体服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SmartDeviceServiceImpl extends ServiceImpl<SmartDeviceMapper, SmartDevice> implements SmartDeviceService {

    private final SmartDeviceTagService tagService;
    private final UserDeviceCollectionMapper collectionMapper;
    private final DeviceVoiceService voiceService;
    private final DeviceApiService apiService;

    @Override
    @Transactional
    public Result<SmartDeviceDTO> createDevice(Long userId, CreateDeviceRequest request) {
        SmartDevice device = new SmartDevice();
        BeanUtils.copyProperties(request, device);

        // 设置创建者ID
        device.setUserId(userId);

        // 生成UUID
        device.setUuid(UUID.randomUUID().toString());

        // 初始化计数器
        device.setUsageCount(0);
        device.setCollectionCount(0);
        device.setAverageRating(BigDecimal.ZERO);
        device.setPromptTokens(0L);
        device.setCompletionTokens(0L);

        // 设置状态和时间
        device.setStatus(1);
        device.setDeleted(0);
        device.setCreatedAt(LocalDateTime.now());
        device.setUpdatedAt(LocalDateTime.now());

        // 保存智能体
        boolean saved = save(device);
        if (!saved) {
            return Result.failed("创建智能体失败");
        }

        // 处理标签关联
        if (request.getTagIds() != null && !request.getTagIds().isEmpty()) {
            tagService.updateDeviceTags(device.getId(), request.getTagIds());
        }

        // 设置创建者名称
        if (userId != null) {
            String nickname = baseMapper.selectUserNicknameById(userId);
            device.setCreatorName(StringUtils.isNotBlank(nickname) ? nickname : "用户" + userId);
        } else {
            device.setCreatorName("系统");
        }

        // 转换为DTO返回
        SmartDeviceDTO dto = convertToDTO(device, userId);
        return Result.success(dto);
    }

    @Override
    @Transactional
    @CacheEvict(value = "device", key = "#request.getId()")
    public Result<SmartDeviceDTO> updateDevice(Long userId, UpdateDeviceRequest request) {
        SmartDevice device = getById(request.getId());
        if (device == null) {
            return Result.failed("智能体不存在");
        }

        // 检查权限
        if (!device.getUserId().equals(userId)) {
            return Result.failed("无权修改此智能体");
        }

        // 更新基本属性
        if (StringUtils.isNotBlank(request.getName())) {
            device.setName(request.getName());
        }
        if (StringUtils.isNotBlank(request.getAvatar())) {
            device.setAvatar(request.getAvatar());
        }
        if (StringUtils.isNotBlank(request.getDescription())) {
            device.setDescription(request.getDescription());
        }
        if (StringUtils.isNotBlank(request.getPrompt())) {
            device.setPrompt(request.getPrompt());
        }
        if (request.getCategoryId() != null) {
            device.setCategoryId(request.getCategoryId());
        }
        if (request.getAiProviderId() != null) {
            device.setAiProviderId(request.getAiProviderId());
        }
        // 将其修改为：
        if (request.getAiModelId() != null) {
            // 将Long类型转换为String类型
            device.setAiModelId(String.valueOf(request.getAiModelId()));
        }
        if (request.getIsPublic() != null) {
            device.setIsPublic(request.getIsPublic());
        }
        if (request.getIsPremium() != null) {
            device.setIsPremium(request.getIsPremium());
        }
        if (request.getMaxContextLength() != null) {
            device.setMaxContextLength(request.getMaxContextLength());
        }
        if (StringUtils.isNotBlank(request.getKnowledgeBaseIds())) {
            device.setKnowledgeBaseIds(request.getKnowledgeBaseIds());
        }
        if (StringUtils.isNotBlank(request.getAbilities())) {
            device.setAbilities(request.getAbilities());
        }

        // 更新语音配置
        if (StringUtils.isNotBlank(request.getVoiceId())) {
            device.setVoiceId(request.getVoiceId());
        }
        if (StringUtils.isNotBlank(request.getVoiceType())) {
            device.setVoiceType(request.getVoiceType());
        }
        if (request.getVoiceSpeedRatio() != null) {
            device.setVoiceSpeedRatio(request.getVoiceSpeedRatio());
        }

        // 更新API配置
        if (StringUtils.isNotBlank(request.getApiEndpointId())) {
            device.setApiEndpointId(request.getApiEndpointId());
        }
        if (StringUtils.isNotBlank(request.getApiKey())) {
            device.setApiKey(request.getApiKey());
        }
        if (StringUtils.isNotBlank(request.getApiBaseUrl())) {
            device.setApiBaseUrl(request.getApiBaseUrl());
        }
        if (request.getApiTimeout() != null) {
            device.setApiTimeout(request.getApiTimeout());
        }
        if (request.getApiRetryTimes() != null) {
            device.setApiRetryTimes(request.getApiRetryTimes());
        }

        if (StringUtils.isNotBlank(request.getExtJson())) {
            device.setExtJson(request.getExtJson());
        }

        // 更新时间
        device.setUpdatedAt(LocalDateTime.now());

        // 保存更新
        boolean updated = updateById(device);
        if (!updated) {
            return Result.failed("更新智能体失败");
        }

        // 处理标签关联
        if (request.getTagIds() != null) {
            tagService.updateDeviceTags(device.getId(), request.getTagIds());
        }

        // 设置创建者名称
        if (device.getUserId() != null) {
            String nickname = baseMapper.selectUserNicknameById(device.getUserId());
            device.setCreatorName(StringUtils.isNotBlank(nickname) ? nickname : "用户" + device.getUserId());
        } else {
            device.setCreatorName("系统");
        }

        // 转换为DTO返回
        SmartDeviceDTO dto = convertToDTO(device, userId);
        return Result.success(dto);
    }

    @Override
    @Transactional
    @CacheEvict(value = "device", key = "#deviceId")
    public Result<Void> deleteDevice(Long userId, Long deviceId) {
        SmartDevice device = getById(deviceId);
        if (device == null) {
            return Result.failed("智能体不存在");
        }

        // 检查权限
        if (!device.getUserId().equals(userId)) {
            return Result.failed("无权删除此智能体");
        }

        // 逻辑删除
        boolean removed = removeById(deviceId);
        if (!removed) {
            return Result.failed("删除智能体失败");
        }

        return Result.success();
    }

    @Override
    @Cacheable(value = "device", key = "#deviceId", unless = "#result.data == null")
    public Result<SmartDeviceDTO> getDeviceDetail(Long deviceId, Long userId) {
        SmartDevice device = getById(deviceId);
        if (device == null || device.getDeleted() == 1) {
            return Result.failed("智能体不存在");
        }

        // 检查访问权限
        if (device.getIsPublic() == 0 && (userId == null || !device.getUserId().equals(userId))) {
            return Result.failed("无权访问此智能体");
        }

        // 获取创建者名称
        if (device.getUserId() != null) {
            String nickname = baseMapper.selectUserNicknameById(device.getUserId());
            device.setCreatorName(StringUtils.isNotBlank(nickname) ? nickname : "用户" + device.getUserId());
        } else {
            device.setCreatorName("系统");
        }

        // 转换为DTO返回
        SmartDeviceDTO dto = convertToDTO(device, userId);
        return Result.success(dto);
    }

    @Override
    public Result<SmartDeviceDTO> getDeviceConfig(Long deviceId, Long userId) {
        Result<SmartDeviceDTO> detailResult = getDeviceDetail(deviceId, userId);
        if (!detailResult.isSuccess()) {
            return detailResult;
        }

        SmartDeviceDTO deviceDTO = detailResult.getData();

        // 获取API配置
        Result<ApiConfigDTO> apiResult = getDeviceApiConfig(deviceId);
        if (apiResult.isSuccess()) {
            // 提取关键信息放入设备DTO
            ApiConfigDTO apiConfig = apiResult.getData();
            deviceDTO.setApiEndpointId(apiConfig.getEndpointId());
            deviceDTO.setApiBaseUrl(apiConfig.getBaseUrl());
            deviceDTO.setApiTimeout(apiConfig.getTimeout());
            deviceDTO.setApiRetryTimes(apiConfig.getRetryTimes());
        }

        // 获取语音配置
        Result<VoiceConfigDTO> voiceResult = getDeviceVoiceConfig(deviceId);
        if (voiceResult.isSuccess()) {
            // 提取关键信息放入设备DTO
            VoiceConfigDTO voiceConfig = voiceResult.getData();
            deviceDTO.setVoiceType(voiceConfig.getVoiceType());
            deviceDTO.setVoiceSpeedRatio(voiceConfig.getSpeedRatio());
        }

        return Result.success(deviceDTO);
    }

    // 添加缓存方法
    @Cacheable(value = "userNickname", key = "#userId", unless = "#result == null")
    public String getCachedUserNickname(Long userId) {
        if (userId == null) {
            return "系统";
        }
        String nickname = baseMapper.selectUserNicknameById(userId);
        return StringUtils.isNotBlank(nickname) ? nickname : "用户" + userId;
    }

    // 添加结果缓存
    @Cacheable(value = "deviceList", key = "#request.toString() + '-' + #userId", unless = "#result.data == null")
    public Result<IPage<SmartDeviceDTO>> pageDevices(DeviceQueryRequest request, Long userId) {
        Page<SmartDevice> page = new Page<>(request.getPage(), request.getSize());

        try {
            IPage<SmartDevice> result;

            // 优化查询逻辑
            if (request.getCategoryId() == null && request.getKeyword() == null && request.getUserId() == null
                    && (request.getIsPublic() == null || request.getIsPublic() == 1)) {
                // 使用索引优化的查询方法
                result = baseMapper.selectPublicDevices(page, request.getSort());
            } else {
                LambdaQueryWrapper<SmartDevice> queryWrapper = buildQueryWrapper(request, userId);
                result = page(page, queryWrapper);

                // 批量获取用户ID
                Set<Long> userIds = result.getRecords().stream()
                        .map(SmartDevice::getUserId)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toSet());

                // 批量获取用户昵称 - 理想情况下应该有一个批量查询方法
                Map<Long, String> nicknameMap = new HashMap<>();
                for (Long uid : userIds) {
                    nicknameMap.put(uid, getCachedUserNickname(uid));
                }

                // 填充创建者名称
                for (SmartDevice device : result.getRecords()) {
                    if (device.getUserId() != null) {
                        device.setCreatorName(nicknameMap.getOrDefault(device.getUserId(), "用户" + device.getUserId()));
                    } else {
                        device.setCreatorName("系统");
                    }
                }
            }

            // 优化DTO转换，减少冗余查询
            IPage<SmartDeviceDTO> dtoPage = result.convert(device -> {
                SmartDeviceDTO dto = new SmartDeviceDTO();
                BeanUtils.copyProperties(device, dto);

                // 这里应该减少对其他服务的调用，比如标签查询
                // 如果有集合字段，使用懒加载

                // 只有当用户已登录时才检查收藏状态
                if (userId != null) {
                    int count = collectionMapper.checkIsCollected(userId, device.getId());
                    dto.setCollected(count > 0);
                } else {
                    dto.setCollected(false);
                }

                return dto;
            });

            return Result.success(dtoPage);
        } catch (Exception e) {
            log.error("查询智能体列表失败", e);
            return Result.failed("查询失败：" + e.getMessage());
        }
    }

    /**
     * 构建查询条件的私有方法
     */
    private LambdaQueryWrapper<SmartDevice> buildQueryWrapper(DeviceQueryRequest request, Long userId) {
        LambdaQueryWrapper<SmartDevice> queryWrapper = new LambdaQueryWrapper<>();

        // 构建查询条件
        queryWrapper.eq(SmartDevice::getDeleted, 0);

        // 关键词搜索
        if (StringUtils.isNotBlank(request.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                    .like(SmartDevice::getName, request.getKeyword())
                    .or()
                    .like(SmartDevice::getDescription, request.getKeyword()));
        }

        // 分类筛选
        if (request.getCategoryId() != null) {
            queryWrapper.eq(SmartDevice::getCategoryId, request.getCategoryId());
        }

        // 创建者筛选
        if (request.getUserId() != null) {
            queryWrapper.eq(SmartDevice::getUserId, request.getUserId());
        }

        // 公开状态筛选
        if (request.getIsPublic() != null) {
            queryWrapper.eq(SmartDevice::getIsPublic, request.getIsPublic());
        } else {
            // 默认只查看公开的或自己创建的
            if (userId != null) {
                queryWrapper.and(wrapper -> wrapper
                        .eq(SmartDevice::getIsPublic, 1)
                        .or()
                        .eq(SmartDevice::getUserId, userId));
            } else {
                queryWrapper.eq(SmartDevice::getIsPublic, 1);
            }
        }

        // 付费状态筛选
        if (request.getIsPremium() != null) {
            queryWrapper.eq(SmartDevice::getIsPremium, request.getIsPremium());
        }

        // 排序
        switch (request.getSort()) {
            case "hot":
                queryWrapper.orderByDesc(SmartDevice::getUsageCount);
                break;
            case "new":
                queryWrapper.orderByDesc(SmartDevice::getCreatedAt);
                break;
            case "rating":
                queryWrapper.orderByDesc(SmartDevice::getAverageRating);
                break;
            default:
                queryWrapper.orderByDesc(SmartDevice::getUpdatedAt);
        }

        return queryWrapper;
    }

    @Override
    public Result<List<SmartDeviceDTO>> getRecommendDevices(Integer limit, Long userId) {
        // 这里可以实现推荐算法，暂时简单返回评分高的
        LambdaQueryWrapper<SmartDevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SmartDevice::getDeleted, 0)
                .eq(SmartDevice::getIsPublic, 1)
                .orderByDesc(SmartDevice::getAverageRating)
                .last("LIMIT " + limit);

        List<SmartDevice> devices = list(queryWrapper);

        // 为结果添加创建者名称
        for (SmartDevice device : devices) {
            if (device.getUserId() != null) {
                String nickname = baseMapper.selectUserNicknameById(device.getUserId());
                device.setCreatorName(StringUtils.isNotBlank(nickname) ? nickname : "用户" + device.getUserId());
            } else {
                device.setCreatorName("系统");
            }
        }

        List<SmartDeviceDTO> dtoList = devices.stream()
                .map(device -> convertToDTO(device, userId))
                .collect(Collectors.toList());

        return Result.success(dtoList);
    }

    @Override
    public Result<List<SmartDeviceDTO>> getHotDevices(Integer limit, Long userId) {
        LambdaQueryWrapper<SmartDevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SmartDevice::getDeleted, 0)
                .eq(SmartDevice::getIsPublic, 1)
                .orderByDesc(SmartDevice::getUsageCount)
                .last("LIMIT " + limit);

        List<SmartDevice> devices = list(queryWrapper);

        // 为结果添加创建者名称
        for (SmartDevice device : devices) {
            if (device.getUserId() != null) {
                String nickname = baseMapper.selectUserNicknameById(device.getUserId());
                device.setCreatorName(StringUtils.isNotBlank(nickname) ? nickname : "用户" + device.getUserId());
            } else {
                device.setCreatorName("系统");
            }
        }

        List<SmartDeviceDTO> dtoList = devices.stream()
                .map(device -> convertToDTO(device, userId))
                .collect(Collectors.toList());

        return Result.success(dtoList);
    }

    @Override
    public Result<List<SmartDeviceDTO>> getLatestDevices(Integer limit, Long userId) {
        LambdaQueryWrapper<SmartDevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SmartDevice::getDeleted, 0)
                .eq(SmartDevice::getIsPublic, 1)
                .orderByDesc(SmartDevice::getCreatedAt)
                .last("LIMIT " + limit);

        List<SmartDevice> devices = list(queryWrapper);

        // 为结果添加创建者名称
        for (SmartDevice device : devices) {
            if (device.getUserId() != null) {
                String nickname = baseMapper.selectUserNicknameById(device.getUserId());
                device.setCreatorName(StringUtils.isNotBlank(nickname) ? nickname : "用户" + device.getUserId());
            } else {
                device.setCreatorName("系统");
            }
        }

        List<SmartDeviceDTO> dtoList = devices.stream()
                .map(device -> convertToDTO(device, userId))
                .collect(Collectors.toList());

        return Result.success(dtoList);
    }

    @Override
    public Result<IPage<SmartDeviceDTO>> getUserDevices(Long userId, Integer page, Integer size) {
        Page<SmartDevice> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<SmartDevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SmartDevice::getUserId, userId)
                .eq(SmartDevice::getDeleted, 0)
                .orderByDesc(SmartDevice::getUpdatedAt);

        IPage<SmartDevice> result = page(pageParam, queryWrapper);

        // 为结果添加创建者名称
        for (SmartDevice device : result.getRecords()) {
            if (device.getUserId() != null) {
                String nickname = baseMapper.selectUserNicknameById(device.getUserId());
                device.setCreatorName(StringUtils.isNotBlank(nickname) ? nickname : "用户" + device.getUserId());
            } else {
                device.setCreatorName("系统");
            }
        }

        IPage<SmartDeviceDTO> dtoPage = result.convert(device -> convertToDTO(device, userId));

        return Result.success(dtoPage);
    }

    @Override
    public Result<IPage<SmartDeviceDTO>> searchDevices(String keyword, Integer page, Integer size, Long userId) {
        Page<SmartDevice> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<SmartDevice> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(SmartDevice::getDeleted, 0)
                .and(wrapper -> wrapper
                        .like(SmartDevice::getName, keyword)
                        .or()
                        .like(SmartDevice::getDescription, keyword));

        // 权限控制
        if (userId != null) {
            queryWrapper.and(wrapper -> wrapper
                    .eq(SmartDevice::getIsPublic, 1)
                    .or()
                    .eq(SmartDevice::getUserId, userId));
        } else {
            queryWrapper.eq(SmartDevice::getIsPublic, 1);
        }

        queryWrapper.orderByDesc(SmartDevice::getUsageCount);

        IPage<SmartDevice> result = page(pageParam, queryWrapper);

        // 为结果添加创建者名称
        for (SmartDevice device : result.getRecords()) {
            if (device.getUserId() != null) {
                String nickname = baseMapper.selectUserNicknameById(device.getUserId());
                device.setCreatorName(StringUtils.isNotBlank(nickname) ? nickname : "用户" + device.getUserId());
            } else {
                device.setCreatorName("系统");
            }
        }

        IPage<SmartDeviceDTO> dtoPage = result.convert(device -> convertToDTO(device, userId));

        return Result.success(dtoPage);
    }

    @Override
    @CacheEvict(value = "device", key = "#deviceId")
    public Result<Void> updateStatus(Long userId, Long deviceId, Integer status) {
        SmartDevice device = getById(deviceId);
        if (device == null) {
            return Result.failed("智能体不存在");
        }

        // 检查权限
        if (!device.getUserId().equals(userId)) {
            return Result.failed("无权修改此智能体状态");
        }

        device.setStatus(status);
        device.setUpdatedAt(LocalDateTime.now());

        boolean updated = updateById(device);
        if (!updated) {
            return Result.failed("更新智能体状态失败");
        }

        return Result.success();
    }

    @Override
    public Result<Void> increaseUsageCount(Long deviceId) {
        int rows = baseMapper.increaseUsageCount(deviceId);
        if (rows <= 0) {
            return Result.failed("增加使用次数失败");
        }
        return Result.success();
    }

    @Override
    @Transactional
    public Result<Void> increaseTokenUsage(Long deviceId, Long promptTokens, Long completionTokens) {
        SmartDevice device = getById(deviceId);
        if (device == null) {
            return Result.failed("智能体不存在");
        }

        device.setPromptTokens(device.getPromptTokens() + promptTokens);
        device.setCompletionTokens(device.getCompletionTokens() + completionTokens);

        boolean updated = updateById(device);
        if (!updated) {
            return Result.failed("更新token使用量失败");
        }

        return Result.success();
    }

    // 添加结果缓存
    @Cacheable(value = "categoryDevices", key = "#categoryId + '-' + #page + '-' + #size + '-' + #userId",
            unless = "#result.data == null || #result.data.records.isEmpty()")
    public Result<IPage<SmartDeviceDTO>> getDevicesByCategory(Long categoryId, Integer page, Integer size, Long userId) {
        Page<SmartDevice> pageParam = new Page<>(page, size);

        try {
            // 使用索引覆盖扫描的优化查询
            IPage<SmartDevice> result;

            // 对于高频访问的公共分类，可以直接使用专用查询方法
            if (categoryId != null && userId == null) {
                // 理想情况下应该有一个优化的联表查询
                result = baseMapper.selectPublicDevicesByCategory(pageParam, categoryId);
            } else {
                // 构建基本查询
                LambdaQueryWrapper<SmartDevice> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.select(SmartDevice::getId, SmartDevice::getName, SmartDevice::getAvatar,
                        SmartDevice::getDescription, SmartDevice::getUserId, SmartDevice::getUsageCount,
                        SmartDevice::getCollectionCount, SmartDevice::getAverageRating);

                queryWrapper.eq(SmartDevice::getDeleted, 0);
                if (categoryId != null) {
                    queryWrapper.eq(SmartDevice::getCategoryId, categoryId);
                }

                // 权限控制
                if (userId != null) {
                    queryWrapper.and(wrapper -> wrapper
                            .eq(SmartDevice::getIsPublic, 1)
                            .or()
                            .eq(SmartDevice::getUserId, userId));
                } else {
                    queryWrapper.eq(SmartDevice::getIsPublic, 1);
                }

                queryWrapper.orderByDesc(SmartDevice::getUsageCount);

                // 执行查询，但只获取基本数据
                result = page(pageParam, queryWrapper);

                // 批量获取用户ID
                Set<Long> userIds = result.getRecords().stream()
                        .map(SmartDevice::getUserId)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toSet());

                // 批量获取用户昵称 - 假设有个批量查询方法
                Map<Long, String> nicknameMap = batchGetUserNicknames(userIds);

                // 填充创建者名称
                for (SmartDevice device : result.getRecords()) {
                    if (device.getUserId() != null) {
                        device.setCreatorName(nicknameMap.getOrDefault(device.getUserId(), "用户" + device.getUserId()));
                    } else {
                        device.setCreatorName("系统");
                    }
                }
            }

            // 优化DTO转换，减少标签等附加数据的查询量
            // 可以考虑延迟加载或按需加载某些非关键数据
            IPage<SmartDeviceDTO> dtoPage = result.convert(device -> {
                SmartDeviceDTO dto = new SmartDeviceDTO();
                BeanUtils.copyProperties(device, dto);

                // 标签等数据按需加载，可以在DTO中添加懒加载标志
                // dto.setTagsLoaded(false);

                // 只计算当前用户的收藏状态
                if (userId != null) {
                    dto.setCollected(isDeviceCollectedByUser(userId, device.getId()));
                } else {
                    dto.setCollected(false);
                }

                return dto;
            });

            return Result.success(dtoPage);
        } catch (Exception e) {
            log.error("获取分类设备列表失败: {}", e.getMessage(), e);
            return Result.failed("获取设备列表失败");
        }
    }

    // 添加缓存方法
    @Cacheable(value = "userCollected", key = "#userId + '-' + #deviceId", unless = "#result == null")
    public boolean isDeviceCollectedByUser(Long userId, Long deviceId) {
        int count = collectionMapper.checkIsCollected(userId, deviceId);
        return count > 0;
    }

    // 批量获取用户昵称的方法
    private Map<Long, String> batchGetUserNicknames(Set<Long> userIds) {
        Map<Long, String> result = new HashMap<>();
        if (userIds.isEmpty()) {
            return result;
        }

        // 理想情况下应该有一个批量查询方法
        // List<UserNameDTO> names = userMapper.batchSelectNicknamesByIds(userIds);

        // 临时方案:使用缓存减少单次查询开销
        for (Long userId : userIds) {
            result.put(userId, getCachedUserNickname(userId));
        }

        return result;
    }

    @Override
    public Result<IPage<SmartDeviceDTO>> getDevicesByTag(Long tagId, Integer page, Integer size, Long userId) {
        // 先查询关联表获取设备ID列表
        LambdaQueryWrapper<SmartDeviceTagRelation> relationQuery = new LambdaQueryWrapper<>();
        relationQuery.eq(SmartDeviceTagRelation::getTagId, tagId);

        List<SmartDeviceTagRelation> relations = tagService.getRelationMapper().selectList(relationQuery);

        if (relations.isEmpty()) {
            return Result.success(new Page<>(page, size));
        }

        List<Long> deviceIds = relations.stream()
                .map(SmartDeviceTagRelation::getDeviceId)
                .collect(Collectors.toList());

        // 查询设备
        Page<SmartDevice> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<SmartDevice> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(SmartDevice::getDeleted, 0)
                .in(SmartDevice::getId, deviceIds);

        // 权限控制
        if (userId != null) {
            queryWrapper.and(wrapper -> wrapper
                    .eq(SmartDevice::getIsPublic, 1)
                    .or()
                    .eq(SmartDevice::getUserId, userId));
        } else {
            queryWrapper.eq(SmartDevice::getIsPublic, 1);
        }

        queryWrapper.orderByDesc(SmartDevice::getUsageCount);

        IPage<SmartDevice> result = page(pageParam, queryWrapper);

        // 为结果添加创建者名称
        for (SmartDevice device : result.getRecords()) {
            if (device.getUserId() != null) {
                String nickname = baseMapper.selectUserNicknameById(device.getUserId());
                device.setCreatorName(StringUtils.isNotBlank(nickname) ? nickname : "用户" + device.getUserId());
            } else {
                device.setCreatorName("系统");
            }
        }

        IPage<SmartDeviceDTO> dtoPage = result.convert(device -> convertToDTO(device, userId));

        return Result.success(dtoPage);
    }

    @Override
    public Result<AIModelInfoDTO> getDeviceAIModel(Long deviceId) {
        SmartDevice device = getById(deviceId);
        if (device == null) {
            return Result.failed("智能体不存在");
        }

        // 这里应该调用AI模型服务获取详细信息
        // 暂时模拟返回
        AIModelInfoDTO modelInfo = new AIModelInfoDTO();
        modelInfo.setModelId(device.getAiModelId());
        modelInfo.setModelName("AI模型" + device.getAiModelId());
        modelInfo.setProviderId(device.getAiProviderId());
        modelInfo.setProviderName("提供商" + device.getAiProviderId());
        modelInfo.setVersion("1.0");
        modelInfo.setMaxContextLength(device.getMaxContextLength());
        modelInfo.setDescription("AI模型描述");
        modelInfo.setCapabilities(device.getAbilities());

        return Result.success(modelInfo);
    }

    @Override
    public Result<ApiConfigDTO> getDeviceApiConfig(Long deviceId) {
        return apiService.getDeviceApiConfig(deviceId);
    }

    @Override
    public Result<VoiceConfigDTO> getDeviceVoiceConfig(Long deviceId) {
        return voiceService.getDeviceVoiceConfig(deviceId);
    }

    /**
     * 将实体转换为DTO，并优化用户信息处理
     *
     * @param device 智能体实体
     * @param userId 当前用户ID
     * @return 转换后的SmartDeviceDTO
     */
    private SmartDeviceDTO convertToDTO(SmartDevice device, Long userId) {
        SmartDeviceDTO dto = new SmartDeviceDTO();
        BeanUtils.copyProperties(device, dto);

        // 使用统一的方法获取用户显示名称
        dto.setCreatorName(getUserDisplayName(device.getUserId()));

        // 设置标签
        Result<List<TagDTO>> tagsResult = tagService.getDeviceTags(device.getId());
        if (tagsResult.isSuccess()) {
            dto.setTags(tagsResult.getData());
        }

        // 设置能力列表
        if (StringUtils.isNotBlank(device.getAbilities())) {
            dto.setAbilities(Arrays.asList(device.getAbilities().split(",")));
        } else {
            dto.setAbilities(new ArrayList<>());
        }

        // 设置知识库ID列表
        if (StringUtils.isNotBlank(device.getKnowledgeBaseIds())) {
            try {
                dto.setKnowledgeBaseIds(
                        Arrays.stream(device.getKnowledgeBaseIds().split(","))
                                .map(Long::parseLong)
                                .collect(Collectors.toList())
                );
            } catch (Exception e) {
                log.warn("解析知识库IDs失败: {}", device.getKnowledgeBaseIds());
                dto.setKnowledgeBaseIds(new ArrayList<>());
            }
        } else {
            dto.setKnowledgeBaseIds(new ArrayList<>());
        }

        // 设置当前用户是否收藏
        if (userId != null) {
            int count = collectionMapper.checkIsCollected(userId, device.getId());
            dto.setCollected(count > 0);
        } else {
            dto.setCollected(false);
        }

        return dto;
    }

    /**
     * 获取用户显示名称的通用方法
     *
     * @param userId 用户ID
     * @return 用户显示名称
     */
    @Override
    public String getUserDisplayName(Long userId) {
        if (userId == null) {
            return "系统";
        }

        try {
            // 直接查询用户昵称
            String nickname = baseMapper.selectUserNicknameById(userId);
            log.debug("用户 {} 昵称查询结果: {}", userId, nickname);

            // 如果昵称为空或null,返回用户名
            if (StringUtils.isBlank(nickname)) {
                nickname = baseMapper.selectUserNameById(userId);
                log.debug("用户 {} 用户名查询结果: {}", userId, nickname);
            }

            // 如果仍然为空,返回默认格式
            return StringUtils.isBlank(nickname) ? "用户" + userId : nickname;
        } catch (Exception e) {
            log.error("获取用户 {} 显示名称时发生错误", userId, e);
            return "用户" + userId;
        }
    }
}